extends Control

class_name InventoryInterface

@onready var inventory_grid: InventoryGrid = $InventoryGrid
@onready var grabbed_slot: PanelContainer = $GrabbedSlot

var grabbed_slot_data: SlotData = null

func _process(delta: float) -> void:
	grabbed_slot.position = get_global_mouse_position() + Vector2(5,5)

func populate_inventory_data(inventory_data: InventoryData) -> void:
	inventory_data.inventory_interaction.connect(on_inventory_interaction)
	inventory_grid.populate_item_grid(inventory_data)

func on_inventory_interaction(
		inventory_data:InventoryData, 
		index: int, 
		buton_index: int
	) -> void:
		var previous_data = inventory_data.get_slot_data(index)
		match [grabbed_slot_data, buton_index]:
			[null, MOUSE_BUTTON_LEFT]:
				grabbed_slot_data = inventory_data.get_slot_data(index)
				grabbed_slot.show()
				grabbed_slot.set_slot_data(grabbed_slot_data)
				inventory_data.set_slot_data(index, null)
			[_, MOUSE_BUTTON_LEFT]:
				if previous_data and previous_data.item_data == grabbed_slot_data.item_data:
					if previous_data.item_data.is_stackable:
						if previous_data.quantity + grabbed_slot_data.quantity < previous_data.item_data.max_stack_amount:
							previous_data.quantity += grabbed_slot_data.quantity
							grabbed_slot_data = null
						else:
							grabbed_slot_data.quantity = grabbed_slot_data.quantity + previous_data.quantity - previous_data.item_data.max_stack_amount
							previous_data.quantity = previous_data.item_data.max_stack_amount
				else:
					inventory_data.set_slot_data(index, grabbed_slot_data)
					grabbed_slot_data = previous_data
			[null, MOUSE_BUTTON_RIGHT]:
				pass
			[_, MOUSE_BUTTON_RIGHT]:
				if previous_data and previous_data.item_data == grabbed_slot_data.item_data:
					if previous_data.quantity < previous_data.item_data.max_stack_amount:
						previous_data.quantity += 1
						grabbed_slot_data.quantity -= 1
						if grabbed_slot_data.quantity == 0:
							grabbed_slot_data = null
				elif not previous_data:
					var slot_data = SlotData.new()
					slot_data.item_data = grabbed_slot_data.item_data
					slot_data.quantity = 1
					grabbed_slot_data.quantity -= 1
					if grabbed_slot_data.quantity == 0:
						grabbed_slot_data = null
					inventory_data.set_slot_data(index, slot_data)
		grabbed_slot.set_slot_data(grabbed_slot_data)
		if grabbed_slot_data:
			grabbed_slot.show()
		else:
			grabbed_slot.hide()
		inventory_grid.populate_item_grid(inventory_data)
